package jxau.jwgl.web.controller;

import jxau.jwgl.commons.WebData;
import jxau.jwgl.commons.entity.User;
import jxau.jwgl.service.ServiceException;
import jxau.jwgl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * UserController
 *
 * @author LongShu 2017/06/04
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public WebData<?> login(HttpServletRequest request, User user) {
        try {
            userService.login(user);
            setSessionAttribute(request, SESSION_USER_KEY, user);
            setSessionAttribute(request, SESSION_GUID_KEY, userService.getGuid(user.getUsername()));

            return WebData.newMsg("登录成功!", user);
        } catch (ServiceException e) {
            return WebData.newError(e.getMessage());
        }
    }

    @GetMapping("myInfo")
    public Object myInfo(HttpServletRequest request) {
        User loginUser = getLoginUser(request);

        if (isAjax(request)) {
            return userService.userInfo(loginUser, loginUser.getUsername());
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("user", loginUser);
        mv.setViewName("user/userInfo");
        return mv;
    }

    @GetMapping("userInfo/{username}")
    public Object userInfo(HttpServletRequest request, @PathVariable String username) {
        User loginUser = getLoginUser(request);

        try {
            Object userInfo = userService.userInfo(loginUser, username);
            return WebData.newObj(userInfo);
        } catch (ServiceException e) {
            return WebData.newError(e.getMessage());
        }
    }

    @GetMapping("/exit")
    public Object exit(HttpServletRequest request) {
        User loginUser = getLoginUser(request);

        request.getSession().invalidate();
        userService.exit(loginUser.getUsername());
        return new ModelAndView(ViewController.getView("login"));
    }

}
